package lib

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"

	"github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi"
)

type SmsServer struct {
	UserName     string `json:"userName"`     //账号账户
	AccessKeyId  string `json:"accessKeyId"`  //授权唯一ID
	AccessSecret string `json:"accessSecret"` //授权秘钥
	TemplateCode string `json:"templateCode"` //模板唯一
	SignName     string `json:"signName"`     //签名名称
	Phone        string `json:"phone"`        //手机号
	Code         string `json:"code"`         //验证码
}

var SmsSend SmsServer

/*
 描述 ： 获取360accessToken
 ******************************************************************************/
func (this *SmsServer) Send() error {
	client, err := dysmsapi.NewClientWithAccessKey(SmsSend.UserName, SmsSend.AccessKeyId, SmsSend.AccessSecret)

	request := dysmsapi.CreateSendSmsRequest()
	request.Scheme = "https"

	request.PhoneNumbers = this.Phone
	request.SignName = SmsSend.SignName
	request.TemplateCode = SmsSend.TemplateCode
	request.TemplateParam = fmt.Sprintf("{'code':'%s'}", this.Code)
	response, err := client.SendSms(request)
	if err != nil {
		fmt.Print(err.Error())
		return err
	}
	fmt.Printf("response is %#v\n", response)
	return err
}

func init() {
	jsonFile, err := os.Open("./config/sms.json")
	if err != nil {
		panic("打开文件错误，请查看:" + err.Error())
	}
	defer jsonFile.Close()
	data, err := ioutil.ReadAll(jsonFile)
	json.Unmarshal(data, &SmsSend)
	if err := SmsSend.Send(); err != nil {
		fmt.Println("发送失败", err.Error())
	}
}
